//
//  XSJAnchorViewController.m
//  XSJ
//
//  Created by Zzz on 2020/5/9.
//  Copyright © 2020 apple. All rights reserved.
//

#import "XSJAnchorViewController.h"
#import "NEReachability.h"

@interface XSJAnchorViewController ()<LSAudioCaptureDelegate>
@property (nonatomic, strong) LSMediaCapture *mediaCapture;
@property (nonatomic, strong) UIView *localPreview;
@end

@implementation XSJAnchorViewController

- (instancetype)initWithPushUrl:(NSString*)url {
    self = [self init];
    if (self) {
        // 初始化直播参数，并创建音视频直播
        LSLiveStreamingParaCtxConfiguration *streamparaCtx = [LSLiveStreamingParaCtxConfiguration defaultLiveStreamingConfiguration];
        streamparaCtx.eOutFormatType               = LS_OUT_FMT_RTMP;
        streamparaCtx.eOutStreamType               = LS_HAVE_AV; //这里可以设置推音视频流／音频流／视频流，如果只推送视频流，则不支持伴奏播放音乐
        streamparaCtx.uploadLog                    = YES;//是否上传sdk日志
        
//        streamparaCtx.sLSVideoParaCtx = paraCtx;
        streamparaCtx.syncTimestamp = YES;//冲顶大会 同步时间戳透传方案
        streamparaCtx.syncTimestampBaseline = YES;
        streamparaCtx.streamTimestampPassthrough = NO;
        streamparaCtx.privateConfig = NO;//私有化配置开关
        
        self.mediaCapture = [[LSMediaCapture alloc]initLiveStream:url withLivestreamParaCtxConfiguration:streamparaCtx];
        self.mediaCapture.audioCaptureDelegate = self;
        if (_mediaCapture == nil) {
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"初始化失败" forKey:NSLocalizedDescriptionKey];
            [self showErrorInfo:[NSError errorWithDomain:@"LSMediaCaptureErrorDomain" code:0 userInfo:userInfo]];
        }
        
        [self.mediaCapture startLiveStream:^(NSError *error) {
            NSLog(@"开始推流");
        }];
        
        [self.mediaCapture startVideoPreview:self.localPreview];
        
        // 请注意：监听对象已修改，不再是_mediaCapture，同时去除原先的SDK_dellloc通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onStartLiveStream:) name:LS_LiveStreaming_Started object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onFinishedLiveStream:) name:LS_LiveStreaming_Finished object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onBadNetworking:) name:LS_LiveStreaming_Bad object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didNetworkConnectChanged:) name:ne_kReachabilityChangedNotification object:nil];
    }
    return self;
}

#pragma mark - Notification
- (void)onStartLiveStream:(NSNotification*)notification {
    NSLog(@"on start live stream");
}

- (void)onFinishedLiveStream:(NSNotification*)notification {
    NSLog(@"on finished live stream");
}

- (void)onBadNetworking:(NSNotification*)notification {
    // 网络不好的情况下，连续一段时间收到这种错误，可以提醒应用层降低分辨率
    NSLog(@"live streaming on bad networking");
}

- (void)didNetworkConnectChanged:(NSNotification *)notify { // 网络监听
    NEReachability *reachability = notify.object;
    NENetworkStatus status = [reachability ne_currentReachabilityStatus];
    switch (status) {
        case ReachableViaWiFi:
            NSLog(@"切换为WiFi网络");
            break;
        case ReachableViaWWAN:
            NSLog(@"切换为移动网络");
            NSLog(@"当前网络为移动网络，是否开启直播");
//            [self.mediaCapture stopLiveStream:^(NSError *error) {
//
//            }];
        case NotReachable:
            NSLog(@"网络已断开，释放资源");
//            [self.mediaCapture stopLiveStream:^(NSError *error) {
//
//            }];
        default:
            break;
    }
}

//显示错误消息
- (void)showErrorInfo:(NSError*)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *errMsg = @"";
        if (error == nil) {
            errMsg = @"推流过程中发生错误，请尝试重新开启";
        } else if ([error class] == [NSError class]){
            errMsg = [error localizedDescription];
        } else {
            NSLog(@"error = %@", error);
        }
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置常亮不锁屏
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    [self.view insertSubview:self.localPreview atIndex:0];
}

- (void)LSavAudioSessionInterruptionBegan {
    NSLog(@"LSavAudioSessionInterruptionBegan");
}

- (void)LSavAudioSessionInterruptionEnded {
    NSLog(@"LSavAudioSessionInterruptionEnded");
}

- (void)LSavAudioSession_20s_NoData {
    NSLog(@"LSavAudioSession_20s_NoData");
}

- (void)LSavAudioSession_AudioFile_EOF {
    NSLog(@"LSavAudioSession_AudioFile_EOF");
}


#pragma mark - Setter && getter
- (UIView *)localPreview {
    if (!_localPreview) {
        _localPreview = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _localPreview.backgroundColor = [UIColor whiteColor];
    }
    return _localPreview;
}
@end
